package com.fourth_groups.shopping121store.ui.home.view;


import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;

import com.fourth_groups.shopping121store.Constants;
import com.fourth_groups.shopping121store.R;
import com.fourth_groups.shopping121store.ui.GoodsDetailActivity;
import com.fourth_groups.shopping121store.ui.home.model.HomeFoodBean;
import com.fourth_groups.shopping121store.ui.home.model.HomeGVBean;
import com.fourth_groups.shopping121store.ui.home.model.HomeLBBean;
import com.fourth_groups.shopping121store.ui.home.model.HomePlBean;
import com.fourth_groups.shopping121store.ui.home.model.HomeXQBean;
import com.fourth_groups.shopping121store.ui.home.presenter.Presenter;

import java.util.ArrayList;
import java.util.List;


/**
 * A simple {@link Fragment} subclass.
 */
public class HomesFragment extends Fragment implements IHomesView {
    private List<HomeFoodBean.DataBean.BlockBean> items;
    private List<HomeFoodBean.DataBean.BlockBean> item;
    private static HomesFragment homesFragment;
    private int sos;
    private int count = 0;
    private int index = 100;
    private HomeRecylerViewAdapter recylerViewAdapter;
    private int id;
    private int ids;
    private AnimRFRecyclerView mRv;
    private AnimationDrawable animationDrawable;
    private ImageView imageView1;
    private HomeListAdapter homeListAdapter;
    private ViewPager mVp;
    private SwipeRefreshLayout srl;
    private ListView mLv;
    private HomesListAdapter homesListAdapter;


    public HomesFragment() {
        // Required empty public constructor
    }

    public static Fragment setFragment() {
        if (homesFragment == null)
            synchronized (HomeFragment.class) {
                if (homesFragment == null) {
                    homesFragment = new HomesFragment();
                }
            }
        return homesFragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        Bundle arguments = getArguments();
        item = new ArrayList<>();
        sos = arguments.getInt("sos");
        id = arguments.getInt("id");
        ids = id;
        if (sos == 0) {
            //关联新布局
            return inflater.inflate(R.layout.fragment_homes_home, container, false);
        } else {
            return inflater.inflate(R.layout.fragment_homes, container, false);
        }
    }

    @Override
    public void onViewCreated(final View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        final Presenter presenter = new Presenter(null, this);
        String url = null;
        switch (sos) {
            case 0:
                Log.i("===", "onCreateView: " + sos);
                url = String.format(Constants.HOME_COMMODITY, count, id);
                break;
            case 1:
                Log.i("===", "onCreateView: " + sos);
                url = String.format(Constants.HOME_COMMODITY, count, id);
                break;
            case 2:
                Log.i("===", "onCreateView: " + sos);
                url = String.format(Constants.HOME_COMMODITY, count, id);
                break;
            case 3:
                Log.i("===", "onCreateView: " + sos);
                url = String.format(Constants.HOME_COMMODITY, count, id);
                break;
            case 4:
                Log.i("===", "onCreateView: " + sos);
                url = String.format(Constants.HOME_COMMODITY, count, id);
                break;
            case 5:
                Log.i("===", "onCreateView: " + sos);
                url = String.format(Constants.HOME_COMMODITY, count, id);
                break;
            case 6:
                Log.i("===", "onCreateView: " + id);
                url = String.format(Constants.HOME_COMMODITY, count, id);
                break;
            case 7:
                Log.i("===", "onCreateView: " + id);
                url = String.format(Constants.HOME_COMMODITY, count, id);
                break;
            case 8:
                Log.i("===", "onCreateView: " + id);
                url = String.format(Constants.HOME_COMMODITY, count, id);
                break;
            case 9:
                Log.i("===", "onCreateView: " + id);
                url = String.format(Constants.HOME_COMMODITY, count, id);
                break;
        }
        presenter.getFoodData(url, sos);
        if (sos == 0) {
            mLv = (ListView) view.findViewById(R.id.home_home_list);
            init();
        } else {
            mRv = (AnimRFRecyclerView) view.findViewById(R.id.homes_recycler_view);
            initView(view, presenter, url);
        }
    }

    private void initView(View view, final Presenter presenter, String url) {
        // View footerView = LayoutInflater.from(getActivity()).inflate(R.layout.home_lv_top, null);
        imageView1 = (ImageView) view.findViewById(R.id.home_xiaozhu);
        srl = (SwipeRefreshLayout) view.findViewById(R.id.home_fragment_srl);
        imageView1.setImageResource(R.drawable.xiaozhu);
        animationDrawable = (AnimationDrawable) imageView1.getDrawable();
        imageView1.setVisibility(View.GONE);

// 添加头部和脚部，如果不添加就使用默认的头部和脚部（头部可以有多个）
        // mRv.addFootView(footerView);
// 设置头部的最大拉伸倍率，默认1.5f，必须写在setHeaderImage()之前
        mRv.setScaleRatio(2.0f);
// 设置下拉时拉伸的图片，不设置就使用默认的

        //LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        //manager.setOrientation(LinearLayoutManager.VERTICAL);
        mRv.setLayoutManager(new AnimRFLinearLayoutManager(getActivity()));
        mRv.setHeaderImageMinAlpha(0.6f);
        mRv.setRefreshEnable(false);
// 设置刷新和加载更多数据的监听，分别在onRefresh()和onLoadMore()方法中执行刷新和加载更多操作

        recylerViewAdapter = new HomeRecylerViewAdapter();
        mRv.setAdapter(recylerViewAdapter);
        recylerViewAdapter.setOnRecyclerViewItemClickListener(new HomeRecylerViewAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position, List<HomeFoodBean.DataBean.BlockBean> mData) {
                Intent intent = new Intent(getActivity(), GoodsDetailActivity.class);
                int id1 = mData.get(position).getItems().get(0).getId();
                // int id = mData.get(0).getItems().get(position).getId();
                Log.d("----", "id---------------------" + id + "id1--------------" + id1);
                intent.putExtra("id", id1);
                startActivity(intent);
            }
        });
        mRv.setLoadDataListener(new AnimRFRecyclerView.LoadDataListener() {
            @Override
            public void onRefresh() {
//                // 开启线程刷新数据
//                String url = String.format(Constants.HOME_COMMODITY, count, id);
//                presenter.getFoodData(url, sos);
            }

            @Override
            public void onLoadMore() {
                imageView1.setVisibility(View.VISIBLE);
                animationDrawable.start();
              //  Log.d("lpx", "来过");
                // 开启线加载更多数据
                count += 10;
                String url = String.format(Constants.HOME_COMMODITY, count, ids);
                presenter.getFoodDatas(url, sos);
            }
        });
//设置进度条颜色
        srl.setColorSchemeResources(R.color.colorAccent, R.color.colorPrimary, R.color.colorPrimaryDark);
        srl.setSize(SwipeRefreshLayout.LARGE);
        srl.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                // 开启线程刷新数据
                imageView1.setVisibility(View.GONE);
                String url = String.format(Constants.HOME_COMMODITY, 0, ids);
                presenter.getFoodData(url, sos);
            }
        });
    }

    private void init() {
        Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what == 1) {
                    mVp.setCurrentItem(msg.arg1);
                }
            }
        };
        View inflate = LayoutInflater.from(getContext()).inflate(R.layout.home_home_rv_top, null);
        mLv.addHeaderView(inflate);
        GridView mGv = (GridView) inflate.findViewById(R.id.home_fragment_gv);
        mVp = (ViewPager) inflate.findViewById(R.id.home_fragment_vp);
        List<Bitmap> bitmaps = new ArrayList<>();
        int[] in = new int[]{R.drawable.qqg, R.drawable.xp, R.drawable.dy99, R.drawable.xwzg, R.drawable.tyg, R.drawable.pt, R.drawable.jdzd, R.drawable.yyg, R.drawable.djz, R.drawable.zbbk,};
        for (int anIn : in) {
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), anIn);
            bitmaps.add(bitmap);
        }
        homeListAdapter = new HomeListAdapter(getActivity(), bitmaps, R.layout.home_fragment_gv);
        mVp.setCurrentItem(index);
        mGv.setAdapter(homeListAdapter);
        mVp.setAdapter(new HomeVpLbAdapter(getActivity()));
        homesListAdapter = new HomesListAdapter(getActivity(), null, R.layout.home_fragment_recyler);
        mLv.setAdapter(homesListAdapter);
        ViewPagerAy viewPagerAy = new ViewPagerAy(handler);
        viewPagerAy.execute();
        final String[] stringArray = new String[]{Constants.QQG, Constants.XP, Constants.DY, Constants.XWZG, Constants.YYG, Constants.PT, Constants.JDZS, Constants.YG, Constants.DDZ, Constants.ZBBR,};
        mGv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getActivity(), HomeDetailsactivity.class);
                intent.putExtra("url", stringArray[position]);
                startActivity(intent);
            }
        });
    }

    @Override
    public void getFoodData(final HomeFoodBean home, final int i) {
        if (getActivity() != null) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (i == 0) {

                    } else {
                        items = home.getData().getBlock();
                        item.addAll(items);
                        recylerViewAdapter.setData(items);
                        mRv.getAdapter().notifyDataSetChanged();
                        mRv.loadMoreComplate();
                        imageView1.setVisibility(View.GONE);
                        animationDrawable.stop();
                        srl.setRefreshing(false);
                    }
                }
            });
        }
    }

    @Override
    public void getFoodDatas(final HomeFoodBean home, final int i) {
        if (getActivity() != null) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (i == 0) {

                    } else {
                        List<HomeFoodBean.DataBean.BlockBean> block = home.getData().getBlock();
                        item.addAll(block);
                        recylerViewAdapter.setData(item);
                        mRv.getAdapter().notifyDataSetChanged();
                        mRv.loadMoreComplate();
                        imageView1.setVisibility(View.GONE);
                        animationDrawable.stop();
                        srl.setRefreshing(false);
                    }
                }
            });
        }
    }

    @Override
    public void getHomeGVData(final List<HomeGVBean> bean, int i) {
        if (getActivity() != null) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
//                    List<HomeGVBean.ItemsBean> homeGVBeen = new ArrayList<>();
//                    for (int j = 0; j < bean.size(); j++) {
//                        List<HomeGVBean.ItemsBean> items = bean.get(j).getItems();
//                        for (int k = 0; k < items.size(); k++) {
//                            homeGVBeen.add(items.get(k));
//                        }
//                    }
//                    homeListAdapter.setData(homeGVBeen);
//                    srl.setRefreshing(false);
                }
            });
        }
    }

    @Override
    public void getHomeLBta(final List<HomeLBBean> bean, int i) {
        if (getActivity() != null) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
//                    List<ImageView> imageViews = new ArrayList<>();
//                    //homeListAdapter.setData();
//                    int size = items.size();
//                    for (int j = 0; j < size; j++) {
//                        String image = bean.get(j).getImage();
//                        ImageView view = new ImageView(getActivity());
//                        Glide.with(getActivity()).load(image).error(R.drawable.hongbao_logo).into(view);
//                        imageViews.add(view);
//                    }
//                    HomeFragmentVPAdapter homeFragmentVPAdapter = new HomeFragmentVPAdapter();
//                    homeFragmentVPAdapter.setImageViews(imageViews);
//                    mVp.setAdapter(homeFragmentVPAdapter);
//                    srl.setRefreshing(false);
                }
            });
        }
    }

    @Override
    public void getHomeXQta(final List<HomeXQBean> bean, int i) {
        if (getActivity() != null) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
//                    //  homeListAdapter.setData(bean.getItems());
//                    homeRecylerViewXQAdapter.setData(bean);
//                    srl.setRefreshing(false);
                }
            });
        }
    }

    @Override
    public void getHomePLta(List<HomePlBean> bean, int i) {
        if (getActivity() != null) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    // homeListAdapter.setData(bean.getItems());
                    srl.setRefreshing(false);
                }
            });
        }
    }

    @Override
    public Context getContexts() {
        return getActivity().getApplicationContext();
    }

    @Override
    public void getFail() {
        if (getActivity() != null) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    srl.setRefreshing(false);
                    animationDrawable.stop();
                }
            });
        }
    }
}
